<template>
  <div class="body">
    <div style="text-align: center;padding: 5px;font-size: 14px" v-if="is_ppt_show">
      <a href="/">返回</a>
    </div>
    <!-- 自定义导航按钮 -->
    <div class="page_navigate" v-if="is_ppt_show">
      <div id="page_creator" class="selected" @click="toPage('creator')">生成PPT</div>
      <div id="page_dashboard" @click="toPage('dashboard')">PPT列表</div>
      <div id="page_customTemplate" @click="toPage('customTemplate')">自定义模板</div>
      <div @click="Teacher()">TeacherPPT教程</div>
    </div>

    <div v-if="!is_ppt_show" style="text-align: center;color: red;font-size: 40px;display: flex;align-items: center;justify-content: center;height: 50vh">PPT生成中....请不要离开</div>

    <!-- 通过代码控制PPT创建 -->
    <div class="input_div" style="display: none">
      <select id="selectType" style="margin-right: 8px" onchange="changeSelectType()">
        <option value="subject">根据主题</option>
        <option value="text">根据内容</option>
        <option value="file">根据文件</option>
        <option value="dataUrl">根据文件链接</option>
        <option value="outline">导入大纲</option>
      </select>
      <textarea id="input_text" placeholder="请粘贴文本内容" rows="5" cols="50" maxlength="6000">{{pptvalue}}</textarea>
      <button style="margin-left: 8px" @click="generate()">生成PPT</button>
    </div>
    <!-- 挂载iframe容器 -->
    <div id="container" :class="[is_ppt_show?'':'ppthide']"></div>
  </div>
</template>

<script>
import "~/js/docmee-ui-sdk-iframe.min.js";
import {useUserStore} from "~/stores/user";
import {LoginPopupTypeEnum} from "~/enums/appEnums";
import {ElMessageBox,ElLoading } from 'element-plus'
import {pptUse} from "~/api/user";
export default {
  name: 'AiPPT',
  data() {
    return {
      loadingInstance: null, // 新增：用于保存Loading实例的引用
      is_ppt_show:false,
      pptvalue:'',
      docmeeUI:'',
      limit: null,
      uid: 95716789,
      currentPage: 'dashboard', // 默认页面
      apiKey: 'ak_uKiSyl356rF5TvETeu', // 替换为你的API密钥
      token: '' // 将在这里动态创建token
    };
  },
  methods: {
    Teacher(){
      window.location.href = 'https://mp.weixin.qq.com/s/VZDlnePQpERXUF8N6FCOWA'
    },
    showLoading(options = {}) {
      this.loadingInstance = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0,0,0,0.5)'
      });
    },

    // 新增：隐藏加载层的方法
    hideLoading() {
      if (this.loadingInstance) {
        this.loadingInstance.close();
        this.loadingInstance = null; // 清空引用，避免内存泄漏
      }
    },
    changeSelectType() {
      let selectTypes = ['subject', 'text', 'file', 'dataUrl', 'outline']
      let selectType = document.getElementById('selectType').value
      for (let i = 0; i < selectTypes.length; i++) {
        let element = document.getElementById('input_' + selectTypes[i])
        element.style.display = (selectType == selectTypes[i] ? 'inline-block' : 'none')
      }
    },
generate() {
  let that = this
  let input =  this.pptvalue
  if (!input) {
    alert('输入不能为空')
    return
  }
  that.docmeeUI.navigate({ page: 'creator' })
  // 根据文本内容
  that.docmeeUI.changeCreatorData({ text: input }, true)
  document.querySelector('#container').style.display = 'block'

},
    async isMoney() {
      const userStore = useUserStore()
      const router = useRouter()
      if(userStore.userInfo.balance < 100 || !userStore.userInfo.balance){
        await ElMessageBox.confirm(
            'T币不足，请获取足够T币后继续使用',
            '提示',
            {
              confirmButtonText: '获取T币',
              cancelButtonText: '暂不使用',
              type: 'warning',
            }
        ).then(() => {
          router.push('/openvip');
        })
            .catch(() => {

            })
        return false;
      }else{
        return true;
      }
    },
    async isTbi() {
      try {
        await ElMessageBox.confirm(
            '智能创作PPT需要消耗100T币',
            '提示',
            {
              showClose: false,
              confirmButtonText: '继续',
              cancelButtonText: '关闭'
            });

        return true;
      } catch (e) {
        return false;
      }
    },
    pptUsePost(){
      pptUse({
        model_id: window.localStorage.getItem('other_id'),
        answer_id:window.localStorage.getItem('answer_id'),
        deduct:100
      }).then((res) => {

      })
    },
    // 创建token
    async createApiToken() {
      let that = this
      if (!this.apiKey) {
        return feedback.msgError('请在代码中设置apiKey：' + resp.message)
      }
      const url = 'https://docmee.cn/api/user/createApiToken'
      const resp = await (await fetch(url, {
        method: 'POST',
        headers: {
          'Api-Key': this.apiKey,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          uid: this.uid,
          limit: null
        })
      })).json()
      if (resp.code != 0) {
        return feedback.msgError('创建接口token异常：' + resp.message)
      }
      this.token = resp.data.token
      // 初始化 UI iframe
      const docmeeUI = new DocmeeUI({
        pptId: null,
        token: this.token, // token
        container: document.querySelector('#container'), // 挂载 iframe 的容器
        page: 'creator', // 'dashboard' ppt列表; 'creator' 创建页面; 'customTemplate' 自定义模版; 'editor' 编辑页（需要传pptId字段）
        lang: 'zh', // 国际化
        mode: 'light', // light 亮色模式, dark 暗色模式
        isMobile: false, // 移动端模式
        hidePdfWatermark:true,// 隐藏水印
        background: 'linear-gradient(-157deg,#f57bb0, #867dea)', // 自定义背景
        padding: '40px 20px 0px',
        onMessage(message) {
          console.log(message)
          if (message.type === 'invalid-token') {
            // 在token失效时触发
            console.log('token 认证错误')
            // 更换新的 token
            let newToken = this.createApiToken(this.apiKey, this.uid, this.limit)
            that.docmeeUI.updateToken(newToken)
          } else if (message.type === 'beforeGenerate') {
            const {subtype, fields} = message.data
            if (subtype === 'outline') {
                  that.docmeeUI.sendMessage({
                    type: 'success',
                    content: '稍等，正在生成PPT...'
                  });
                  return true;
            } else if (subtype === 'ppt') {
              // 返回 Promise 以实现异步拦截
              return new Promise(async (resolve) => {
                try {
                  const is_zhu = await that.isMoney(); // 等待异步验证
                  if (!is_zhu) {
                    resolve(false);
                    return;
                  }

                  const is_ty = await that.isTbi(); // 顺序执行第二个验证
                  if (!is_ty) {
                    resolve(false);
                    return;
                  }

                  that.docmeeUI.sendMessage({
                    type: 'success',
                    content: '继续生成PPT'
                  });
                  resolve(true); // 验证通过
                  //调用扣除T币的方法
                  that.pptUsePost()
                } catch (error) {
                  console.error('验证失败:', error);
                  resolve(false);
                }
              });
            }
          } else if (message.type === 'beforeCreateCustomTemplate') {
            const {file, totalPptCount} = message.data
            // 是否允许用户继续制作PPT
            //return feedback.msgError('用户自定义完整模版，PPT文件：', file.name)
            if (totalPptCount < 2) {
              return ElMessageBox.confirm(
                  '用户生成积分不足，不允许制作自定义完整模版',
                  '提示',
                  {
                    showClose: false,
                    showCancelButton:false,
                    confirmButtonText: '知道了',
                    cancelButtonText: '关闭'
                  });
            }else {
              return true
            }
          } else if (message.type == 'pageChange') {
            that.pageChange(message.data.page)
          } else if (message.type === 'beforeDownload') {
            // 自定义下载PPT的文件名称
            const {id, subject} = message.data
            return `PPT_${subject}.pptx`
          } else if (message.type == 'error') {
            if (message.data.code == 88) {
              // 创建token传了limit参数可以限制使用次数
              return feedback.msgError('您的次数已用完')
            } else {
              return feedback.msgError('发生错误：' + message.data.message)
            }
          }else if(message.type == 'toggleGenerateMode'){
            setTimeout(function (){
               that.is_ppt_show = true
               that.hideLoading(); // 隐藏加载层
            },6000)
          }
        }
      })
      this.docmeeUI = docmeeUI
      if(this.pptvalue) {
        setTimeout(function () {
          that.generate()
        }, 3000)
      }
    },
    toPage(page) {
      this.docmeeUI.navigate({ page })
      this.pageChange(page)
    },
    pageChange(page) {
      let element = document.getElementById('page_' + page)
      if (element) {
        element.parentNode.childNodes.forEach(c => c.classList && c.classList.remove('selected'))
        element.classList.add('selected')
      }
    }
  },
  mounted() {
    let that = this
    this.showLoading({ text: '请稍等....' })
    this.pptvalue = window.localStorage.getItem('ppt_str')
    const userStore = useUserStore()
    this.uid = userStore.userInfo.id
    if(this.uid > 0){
      this.createApiToken(); // 创建token
    }else{
      userStore.setLoginPopupType(LoginPopupTypeEnum.LOGIN)
      userStore.toggleShowLogin(true)
    }
  }
};
</script>

<style scoped>
.body {
  margin: 0;
  width: 90vw;
  height: 100vh;
}

.page_navigate {
  padding: 5px;
  height: 45px;
  width: calc(100% - 50px);
  display: flex;
  justify-content: center;
  align-items: center;
}

.page_navigate > div {
  padding: 8px 16px;
  margin-right: 8px;
  cursor: pointer;
  user-select: none;
  border: 2px solid #f0f0f0;
  border-radius: 6px;
}

.page_navigate .selected {
  background: #f57bb0;
}

#container {
  width: calc(100% - 50px);
  height: calc(100% - 100px);
  margin: 0 auto;
  padding: 0;
  border-radius: 12px;
  box-shadow: 0 0 12px rgba(120, 120, 120, 0.3);
  overflow: hidden;
  background: linear-gradient(-157deg, #f57bb0, #867dea);
  color: white;
}
.ppthide {
  visibility: hidden;
}
</style>
